﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Perceiveit.Xml.Tests
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private PerformanceSet _set = new PerformanceSet();

        private void buttonRun_Click(object sender, EventArgs e)
        {
            try
            {
                this.bindingSource1.DataSource = _set;
                if (this.rbXEntity.Checked)
                    RunXEntityTests();
                else if (this.rdXmlSerializer.Checked)
                    RunXmlSerializerTests();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not complete the tests : " + ex.Message);
            }
        }

        private void RunXmlSerializerTests()
        {
            Serialized.XSerializerPerformance perf = new Perceiveit.Xml.Tests.Serialized.XSerializerPerformance();
            PerformanceRun set = perf.TestPerformance();
            foreach (PerformanceMarker marker in set.Markers)
            {
                this.AddMarkerToSet(marker);
            }
            this.bindingSource1.ResetBindings(false);
        }

        private void RunXEntityTests()
        {
            Linq.XEntityPerformance perf = new Perceiveit.Xml.Tests.Linq.XEntityPerformance();
            PerformanceRun set = perf.TestPerformance();

            foreach (PerformanceMarker marker in set.Markers)
            {
                this.AddMarkerToSet(marker);
            }
            this.bindingSource1.ResetBindings(false);
        }

        private void AddMarkerToSet(PerformanceMarker marker)
        {
            PerformanceSetResult result;
            if(!this._set.TryGetResult(marker.Category,marker.Action,out result))
            {
                result = new PerformanceSetResult();
                result.AddResult(marker);
                this._set.Add(result);
            }
            else
                result.AddResult(marker);
        }

        private void butExport_Click(object sender, EventArgs e)
        {
            if (this.saveFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                string path = this.saveFileDialog1.FileName;
                ExportToCSV<PerformanceSetResult> exporter = new ExportToCSV<PerformanceSetResult>();

                try
                {
                    exporter.Export(path, _set);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Could not export to CSV : " + ex.Message);
                }
            }
        }
    }
}
